<?php

namespace cms\modules\v1\models;

use cms\modules\v1\models\admin\Admin;
use cms\modules\v1\models\admin\AdminRole;
use cms\modules\v1\models\user\User;
use common\models\Common;
use common\models\Functions;
use common\models\shop\GoodsOrder;
use common\models\Status;
use common\models\userFund\UserMoney;
use common\models\userFund\UserRechargeOrder;
use common\models\userFund\UserWithdrawOrder;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * 首页信息处理逻辑
 * Class Home
 * @package cms\modules\v1\models
 */
class Home extends Common
{
    /**
     * 获取首页信息
     * @return array
     */
    public function getHomeCardData()
    {
        try {
            $adminInfo = (new Admin())->checkLogin();
            $where['id'] = $adminInfo['role_type'];

            if ($adminInfo['role_type'] != 1) {
                $role = AdminRole::getOneInfoById($adminInfo['role_type']);
                $type = explode(',',$role['role_permissions']);
                if(!in_array(1,$type)){
                    $data = [
                        ["span" => 24, "name" => "欢迎登陆龙邻管理系统", "value" => $adminInfo['nick_name'] . ", 尊敬的用户您好，欢迎您，开心每一天！"],
                    ];
                    return Functions::formatRestAPI(0, '', $data);
                }
            }

            $cache = \Yii::$app->cache;
            $data = $cache->get("HOME_CARD_DATA");

            if ($data) {
                return Functions::formatRestAPI(0, '', $data);
            }

            $span = 4;
            $today = date("Y-m-d");
            $yes = date("Y-m-d", strtotime("-1 days"));

            $userWithdrawOrderModel = new UserWithdrawOrder();
            $rechargeTotal = UserRechargeOrder::getSumByWhere(['status' => Status::RECHARGE_STATUS_DONE],'money');
            $goodsOrderTotal = GoodsOrder::getSumByWhere([
                'status' => [
                    Status::USER_GOODS_ORDER_STATUS_WAITING_SEND,
                    Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE,
                    Status::USER_GOODS_ORDER_STATUS_DONE,
                ],
                'pay_way' => Status::PAY_WAY_ALIPAY,
            ],'real_money');
//            $rechargeTotal = UserRechargeOrder::getSumByAndWhere(['status' => Status::RECHARGE_STATUS_DONE],['>','create_time',"2023-02-01 00:00:00"],'money');
            $rechargeCount = UserRechargeOrder::getCountByWhere(['status' => Status::RECHARGE_STATUS_DONE]);
//            $rechargeCount = UserRechargeOrder::getCountByAndWhere(['status' => Status::RECHARGE_STATUS_DONE],['>','create_time',"2023-02-01 00:00:00"]);
            $withdrawTotal = $userWithdrawOrderModel::getSumByWhere(['status' => Status::COMMON_CHECKING_SUCCESS],'money');
            $withdrawCount = $userWithdrawOrderModel::getCountByWhere(['status' => Status::RECHARGE_STATUS_DONE]);
            $withdrawBankCount = $userWithdrawOrderModel::getCountByWhere(['status' => Status::RECHARGE_STATUS_DONE,'withdraw_way' => Status::WITHDRAW_WAY_BANK]);

            $data = [
                ["span" => 8, "name" => "总用户人数", "value" => (int)User::getCountByWhere()],
                ["span" => 8, "name" => "今日新增用户", "value" => $this->_getTotalUser()],
                ["span" => 8, "name" => "昨日新增用户", "value" => $this->_getTotalUser($yes)],
                ["span" => 12, "name" => "充值金额", "value" => sprintf("%01.2f",$rechargeTotal + $goodsOrderTotal)?:0],
                ["span" => 12, "name" => "充值笔数", "value" => sprintf("%01.2f",$rechargeCount)?:0],
                ["span" => 12, "name" => "提现金额", "value" => sprintf("%01.2f",$withdrawTotal)?:0],
                ["span" => 12, "name" => "提现笔数", "value" => sprintf("%01.2f",$withdrawCount)?:0],
            ];

            $userMoneyModel = new UserMoney();
            # 总余额
            $money = $userMoneyModel::getSumByWhere(['prop_id' => Status::PROP_TYPE_MONEY],'num');
            $shopMoney = $userMoneyModel::getSumByWhere(['prop_id' => Status::PROP_TYPE_SHOP_MONEY],'num');
            $totalMoney = sprintf("%01.2f",($money - $shopMoney));
//            $data[] = ["span" => $span, "name" => "总余额", "value" => $totalMoney];
//            $data[] = ["span" => $span, "name" => "钱包余额", "value" => $money];
//            $data[] = ["span" => $span, "name" => "橱窗余额", "value" => $shopMoney];
//            $data[] = ["span" => $span, "name" => "余额提现", "value" => sprintf("%01.2f",$userWithdrawOrderModel::getSumByWhere([
//                'status' => Status::COMMON_CHECKING_SUCCESS,
//                'type' => Status::WITHDRAW_TYPE_MONEY,
//            ],'money'))?:0];
//            $data[] = ["span" => $span, "name" => "橱窗提现", "value" => sprintf("%01.2f",$userWithdrawOrderModel::getSumByWhere([
//                'status' => Status::COMMON_CHECKING_SUCCESS,
//                'type' => Status::WITHDRAW_TYPE_SHOP,
//            ],'money'))?:0];


            // 用户总余额 = 充值金额 - 提现金额
            $userTotalMoney = $rechargeTotal + $goodsOrderTotal - $withdrawTotal;
            $data[] = ["span" => 8, "name" => "用户总余额", "value" => sprintf("%01.2f",$userTotalMoney)?:0];
//            $data[] = ["span" => 8, "name" => "用户总余额", "value" => sprintf("%01.2f",$totalMoney)?:0];
            $data[] = ["span" => 8, "name" => "零钱", "value" => sprintf("%01.2f",$money)?:0];
            $data[] = ["span" => 8, "name" => "橱窗余额", "value" => sprintf("%01.2f",$shopMoney)?:0];

            // 平台支出一  ：充值金额✖️0.006元
            // 平台支出二  ：提现总金额✖️0.006
            // 平台支出二  ：打款到卡每笔✖️2元
            // 平台总支出  ：一 + 二 + 三
            $consumeOne = sprintf("%01.2f",$rechargeTotal * 0.006);
            $consumeTwo = sprintf("%01.2f",$withdrawTotal * 0.006);
            $consumeThree = sprintf("%01.2f",$withdrawBankCount * 2);
            $consumeTotal = sprintf("%01.2f",$consumeOne + $consumeTwo + $consumeThree);
            $data[] = ["span" => 6, "name" => "平台支出(充值)", "value" => $consumeOne];
            $data[] = ["span" => 6, "name" => "平台支出(提现)", "value" => $consumeTwo];
            $data[] = ["span" => 6, "name" => "平台支出(短信)", "value" => $consumeThree];
            $data[] = ["span" => 6, "name" => "合计支出", "value" => $consumeTotal];

            // 平台总余额 充值金额 - 充值金额*0.006 - 提现金额 *0.956 + 提现31笔，31元 - 减去打款6笔银行卡 * 2
            $totalMoney = sprintf("%01.2f",($rechargeTotal - $rechargeTotal*0.006 - $withdrawTotal * 0.956  +  $withdrawCount * 1 - $withdrawBankCount * 2));
            $data[] = ["span" => 12, "name" => "平台总金额", "value" => $totalMoney];

            // 平台收入:[提现金额*(0.05-0.006) - (充值金额一充值金额*0.006) - 提现银行卡笔数*2元
            $incomeTotal = sprintf("%01.2f",($withdrawTotal*(0.05-0.006) - ($rechargeTotal * 0.006) - $withdrawBankCount * 2));

            $data[] = ["span" => 12, "name" => "平台收入", "value" => $incomeTotal];




            //1分钟更新一次 * 5
            $cache->set("HOME_CARD_DATA", $data, 5*60);
            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }

    }

    private function _getTotalUser($date = '')
    {
        if (empty($date)) {
            $date = date("Y-m-d");
        }
        $start = $date . " 00:00:00";
        $end = $date . " 23:59:59";

        #获取昨日新增客户
        $andWhere = [];
        $andWhere[] = ["between", "register_time", $start, $end];

        return User::getCountByAndWhere([], $andWhere);
    }

    public function getList() {
        $key = "API_STATISTIC:*";

        $redis = \Yii::$app->get("redis");

        $get = \Yii::$app->request->get();

        $keys = $redis->keys($key);
        $res = [];
        foreach ($keys as $v) {
            $keys = $redis->hkeys($v);
            $tmp = [];
            foreach ($keys as $vv) {
                $value = $redis->hget($v, $vv);
                $tmp[$vv] = $value;
            }

            $res[] = $tmp;
        }

        ArrayHelper::multisort($res, $get['order'], SORT_DESC);
        return Functions::formatRestAPI(0, '', $res);
    }
}
